package xp2p.svc.file;

import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import xp2p.adv.jxta.FileAdv;
import xp2p.svc.ListenerBase;
import net.jxta.content.ContentID;

/**
 * The Class FileFinder. simple file advertisement listener, stores ContentIDs
 * for each file so they could be downloaded by peers in peergroup
 */
public class FileFinder extends ListenerBase<FileAdv>
{
	private FoundHandler handler;
	public String ftype = "file";

	public FileFinder(FoundHandler handler)
	{
		this.ftype = handler.getFType();
		this.handler = handler;
		this.setDocType(FileAdv.DocType);
		this.setAdvClassType(FileAdv.class.getName());
	}

	/** The sync. */
	private Object sync = new Object();

	/** The found. */
	private HashMap<String, Set<ContentID>> found = new HashMap<String, Set<ContentID>>();

	/**
	 * Adds the file.
	 * 
	 * @param name
	 *            the name
	 */
	public void AddFile(String name)
	{
		synchronized (sync)
		{
			if (!found.containsKey(name))
			{
				found.put(name, new HashSet<ContentID>());
			}
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see xp2p.services.ListenerBase#process(net.jxta.document.Advertisement)
	 */
	@Override
	protected void process(FileAdv a)
	{
		synchronized (sync)
		{
			if (a.getFType().compareTo(ftype) == 0)
			{
				if (!getFound().containsKey(a.getName()))
				{
					getFound().put(a.getName(), new HashSet<ContentID>());
				}
				getFound().get(a.getName()).add(a.getContentID());
			} else
				return;
		}
		handler.Handle(a.getContentID(), a.getName());
	}

	/**
	 * Gets the found.
	 * 
	 * @return the found
	 */
	public Map<String, Set<ContentID>> getFound()
	{
		return found;
	}

	/**
	 * Found everything.
	 * 
	 * @return true, if successful
	 */
	public boolean FoundEverything()
	{
		synchronized (sync)
		{
			Collection<Set<ContentID>> keys = found.values();
			for (Set<ContentID> s : keys)
			{
				if (s.isEmpty())
				{
					return false;
				}
			}
			return true;
		}
	}

	public boolean Found(String name)
	{
		synchronized (sync)
		{
			return found.get(name).isEmpty();
		}
	}

	public FoundHandler getHandler()
	{
		return handler;
	}

	public void setHandler(FoundHandler handler)
	{
		this.handler = handler;
	}
}
